Conditionals
I. Comparison
Resources
All comparison operators return a boolean value, true
or 1
, false
, or 0
. We often use comparison to compare numbers, but there are a few special comparisons that we can perform:
1. String Comparison:
To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order.
console.log('Z' > 'A'); // true
console.log('B' > 'AC'); // true, because 'B' > 'A' -> stopped checking and return true without checking 'C'
console.log('Hello!' > 'Hello!!!'); // if the prior characters are the same, the longer string is greater
The algorithm to compare two strings is:
- Compare the first character of both strings.
- If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
- Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
- Repeat until the end of either string.
- If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
2. Comparison of Different Types:
When comparing values of different types, JavaScript converts the values to a comparable type.
Example:
console.log('2' > 1); // true, because string '2' is converted to number 2
console.log('01' == 1); // true, because string '01' is converted to number 1
console.log(true == 1); // true
console.log(false == 0); // true
console.log('' == 0); // true -> empty string equals 0
console.log('' == false); // true -> empty string equals false
console.log('' != 1); // true
- [[01. Variables & Operators#^e47ca1|Strict equality]]
===
checks for equality in both value and data type.
console.log(true === 1); // false, because they're different type
console.log('' === 0); // false
console.log('' === false); // false
// this also applies to strict non-equality
console.log('' !== true); // true
3. Comparing null
and undefined
- Strict equality check:
console.log(null === undefined); // false
- Non-strict equality check:
console.log(null == undefined); // true
4. Comparing null
and 0
In JavaScript, an equality check ==
and comparisons > < >= <=
work differently.
- Comparisons convert
null
to a number, treating it asO
. - The equality check
==
does not convert to a number,null == undefined
, and nothing else.
console.log(null > 0); // false
console.log(null == 0); // false
console.log(null >= 0); // true
5. An incomparable undefined
undefined
should never be compared to other values:
console.log(undefined > 0); // false
console.log(undefined < 0); // false
console.log(undefined == 0); // false
Note:
- Treat any comparison with
undefined/null
except the strict equality===
with exceptional care.- Don’t use comparisons
>= > < <=
with a variable that may benull/undefined
, unless you’re sure of what you’re doing. If a variable can have these values, check for them separately.
Summary
- Comparison operators return a boolean value.
- Strings are compared letter-by-letter in the “dictionary” order.
- When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
- The values
null
andundefined
equal==
each other and do not equal any other value. - Be careful when using comparisons like
>
or<
with variables that can occasionally benull/undefined
. Checking fornull/undefined
separately is a good idea.
II. Conditional Statements
Resources:
In JavaScript we have the following conditional statements:
- Use
if
to specify a block of code to be executed, if a specified condition is true - Use
else
to specify a block of code to be executed, if the same condition is false - Use
else if
to specify a new condition to test, if the first condition is false - Use
switch
to specify many alternative blocks of code to be executed
1. if
statement
Use the if
statement to specify a block of JavaScript code to be executed if a condition is true.
// syntax
if (_condition_) {
// _block of code to be executed if the condition is true_
}
if (hour < 18) {
greeting = "Good day";
}
2. else
statement
Use the else
statement to specify a block of code to be executed if the condition is false.
// syntax
if (_condition_) {
// _block of code to be executed if the condition is true_
}
else {
// _block of code to be executed if the condition is false_
}
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
3. else if
statement
Use the else if
statement to specify a new condition if the first condition is false.
// syntax
if (_condition1_) {
// _block of code to be executed if condition1 is true_
} else if (_condition2_) {
// _block of code to be executed if the condition1 is false and condition2 is true_
} else {
// _block of code to be executed if the condition1 is false and condition2 is false_
}
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
4. switch
statement
Use the switch
statement to select one of many code blocks to be executed.
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the
default
code block is executed.
// syntax
switch(_expression_) {
case _x_:
_// code block_
break;
case _y_:
_// code block_
break;
default:
// _code block_
}
switch (date) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
1. break
keyword
- When JavaScript reaches a
break
keyword, it breaks out of the switch block → stop the execution inside the switch block. - It is not necessary to break the last case in a switch block, the block breaks (ends) there anyway.
Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
2. Common Code Blocks
Sometimes you will want different switch cases to use the same code.
// case 4 and 5 share the same code block, 0 and 6 share another code block
switch (date) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
Note:
- If multiple cases matches a case value, the first case is selected.
- If no matching cases are found, the program continues to the default label.
- If no default label is found, the program continues to the statement(s) after the switch.
- Switch cases use strict comparison
===
→ the values must be of the same type of match
5. Conditional Operator ?
The conditional operator ?
lets us write the conditional block in a shorter way.
// syntax
condition ? expression1 : expression2
let message;
// a conditional block
if(age > 18){
message = "You are an adult!";
} else{
message = "You are not yet an adult!";
}
// using the conditional operator
let message = (age > 18) ? "You are an adult!" : "You are not yet an adult!";
III. Logical Operators
There are four logical operators in JavaScript: ||
(OR), &&
(AND), !
(NOT), ??
(Null-ish Coalescing).
1. ||
(OR)
In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true
, it returns true
, otherwise it returns false
.
console.log(true || true); // true
console.log(false || true); // true
console.log(true || false); // true
console.log(false || false); // false
Most of the time, OR ||
is used in an if
statement to test if any of the given conditions is true
.
let hour = 9;
if (hour < 10 || hour > 18) {
console.log('The office is closed.');
}
1. Finds the first truthy value
The OR ||
operator does the following:
- Evaluates operands from left to right.
- For each operand, converts it to boolean. If the result is
true
, stops and returns the original value of that operand. - If all operands have been evaluated (i.e. all were
false
), returns the last operand.
A value is returned in its original form, without the conversion.
→ A chain of OR ||
returns the first truthy value or the last one if no truthy value is found.
console.log(1 || 0); // 1 (1 is truthy)
console.log(null || 1); // 1 (1 is the first truthy value)
console.log(undefined || null || 0); // 0 (all falsy, 0 is he last value)
We can use OR ||
to do the following:
let firstName = ""; // falsy because empty
let lastName = "";
let nickName = "Yo!"; // truthy
console.log(firstName || lastName || nickName || "Someone");
// output: "Yo!"
// if all variables were falsy, output: "Someone"
2. Short-circuit Evaluation
true || console.log("This isn't printed");
false || console.log("This is printed");
→ This feature allows executing commands only if the condition on the left is falsy.
2. &&
(AND)
In classical programming, AND returns true
if both operands are truthy and false
otherwise:
console.log(true && true); // true
console.log(false && true); // false
console.log(true && false); // false
console.log(false && false); // false
Using &&
with if
statement:
let hour = 12;
let minute = 30;
if (hour == 12 && minute == 30){
console.log("The time is 12:30");
}
1. AND &&
finds the first falsy value
The AND &&
operator does the following:
- Evaluates operands from left to right.
- For each operand, converts it to a boolean. If the result is
false
, stops and returns the original value of that operand. - If all operands have been evaluated (i.e. all were truthy), returns the last operand.
// returns first falsy value
console.log(1 && 0); // 0
console.log(1 && 5); // 5
console.log(null && 5); // null
console.log(0 && "something"); // 0
// all values are truthy, so the last value is returned
console.log(1 && 2 && 3); // 3
2. Precedence of AND &&
The precedence of AND &&
operator is higher than OR ||
. So the code a && b || c && d
is essentially the same as if the &&
expressions were in parentheses: (a && b) || (c && d)
.
3. !
(NOT)
The boolean NOT operator is represented with an exclamation sign !
.
result = !value;
The operator accepts a single argument and does the following:
- Converts the operand to boolean type:
true/false
. - Returns the inverse value.
console.log(!true); // false
console.log(!0); // true
A double NOT !!
is sometimes used for converting a value to boolean type:
console.log(!!"non-empty string"); // true
console.log(!!null); // false
// the equivalent
console.log(Boolean("non-empty string")); // true
console.log(Boolean(null)) // false
The precedence of NOT
!
is the highest of all logical operators → it’s always executed first.